var holdTimeStart = 0,
  img_id = 0,
  imgList = [],
  page_id = getQueryString('id'),
  currentImg = 0

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = (window.location.hash || window.location.search).substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

function startHold() {
  holdTimeStart = new Date().getTime()
}

function endHold() {
  if (holdTimeStart > 0 && new Date().getTime() - holdTimeStart >= 500) jvRecordLog('handle')
  holdTimeStart = 0
}

function geiImg() {
  $.ajax({
    type: 'GET',
    url: 'http://www.drinkt.org.cn/page/getimg',
    crossDomain: true,
    dataType: 'json',
    data: {
      page_id: page_id,
      rnd: Math.random()
    },
    xhrFields: {
      'Access-Control-Allow-Origin': '*'
    },
    success: function(result) {
      const title = result.data.title || '海岛小阿妹'
      document.title = title
      imgList = result.data.img_list.sort(function() {
        return 0.5 - Math.random()
      })
      result.data.length && (img_id = imgList[0].id)
      replaceWxInfo()
      jvRecordLog('access')
    }
  })
}

function replaceWxInfo() {
  var length = imgList.length
  if (length === 0) {
    return
  }
  if (currentImg >= length) {
    currentImg = 0
  }
  $('.wx').attr('src', imgList[currentImg].img_path)
  // $('.wx').attr('src', 'http://wechat-img.szxywhcm.com/wechat_qrcode2/39/3c44c8967abaffae9b80f7fb6c5db2d4.jpg')
  img_id = imgList[currentImg].id
  currentImg++
}

function jvRecordLog(type, v) {
  $.ajax({
    type: 'POST',
    url: 'http://www.drinkt.org.cn/log/count',
    crossDomain: true,
    dataType: 'json',
    data: {
      page_id: page_id,
      img_id: img_id,
      type: type,
      rnd: Math.random()
    },
    xhrFields: {
      'Access-Control-Allow-Origin': '*'
    },
    success: function(result) {
      if (type !== 'access') replaceWxInfo()
    }
  })
}

$(function() {
  $('.wx')
    .on('touchstart', startHold)
    .on('mousedown', startHold)
    .on('taphold', function() {
      jvRecordLog('handle')
    })
    .on('touchend', endHold)
    .on('mouseup', endHold)
})
geiImg()
